﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Organizations;
using Abp.UI;
using Camc.Quality.Authorization.Roles;
using Camc.Quality.Bop;
using Camc.Quality.Inspection;
using Camc.Quality.WorkFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Camc.Quality.QualityManage
{
    public class QualityManageAppService : QualityAppServiceBase
    {
        private readonly IRepository<QualitySeverityDesc, Guid> _qualitySeverityDescRepository;
        private readonly IRepository<QualitySeverityRole, Guid> _qualitySeverityRoleRepository;
        private readonly IRepository<QualityTypeDesc, Guid> _qualityTypeDescRepository;
        private readonly IRepository<QualityItemInfo, Guid> _qualityItemInfoRepository;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly RoleManager _roleManager;
        private readonly IRepository<AffairRemind, int> _affairRemindRepository;
        public QualityManageAppService(IRepository<QualitySeverityDesc, Guid> qualitySeverityDescRepository,
                                         IRepository<QualitySeverityRole, Guid> qualitySeverityRoleRepository,
                                         IRepository<QualityTypeDesc, Guid> qualityTypeDescRepository,
                                         IRepository<QualityItemInfo, Guid> qualityItemInfoRepository, 
                                         IRepository<OrganizationUnit, long> organizationUnitRepository,
                                         RoleManager roleManager,
                                         IRepository<AffairRemind, int> affairRemindRepository
            )
        {
            _qualitySeverityDescRepository = qualitySeverityDescRepository;
            _qualitySeverityRoleRepository = qualitySeverityRoleRepository;
            _qualityTypeDescRepository = qualityTypeDescRepository;
            _qualityItemInfoRepository = qualityItemInfoRepository;
            _organizationUnitRepository = organizationUnitRepository;
            _roleManager = roleManager;
            _affairRemindRepository = affairRemindRepository;
        }
        /// <summary>
        /// 角色下拉列表
        /// </summary>
        /// <returns></returns>
        public List<RoleNameListDto> GetRoleManagerNameList()
        {
            var nameList = _roleManager.Roles.ToList();
            if (nameList != null)
            {
                var roleNameListDto = ObjectMapper.Map<List<RoleNameListDto>>(nameList);
                return roleNameListDto;
            }
            else
            {
                throw new UserFriendlyException("");
            }
        }
        /// <summary>
        /// 不良严重等级查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<QualitySeverityDescOutDto>> GetQualitySeverityDescList(GetQualitySeverityDescInput input)
        {
            var severityDesc =from qsd in _qualitySeverityDescRepository.GetAll().Where(s => s.IsUsed != InspectionItemInfo.IsUseds.已删除)
                              join arr in _affairRemindRepository.GetAll()
                              on qsd.Id.ToString() equals arr.AffairCode
                              select new QualitySeverityDescOutDto
                              {
                                  Id = qsd.Id,
                                  SeverityName = qsd.SeverityName,
                                  SeverityDesc = qsd.SeverityDesc,
                                  IsUsed = (int)qsd.IsUsed,
                                  CCRole = arr.RoleListDesc,
                                  CreationTime = qsd.CreationTime
                              }; 
            var count = severityDesc.Count();
            severityDesc = severityDesc.OrderByDescending(e => e.CreationTime).PageBy(input);
            return new PagedResultDto<QualitySeverityDescOutDto>(count, severityDesc.ToList());
        }
        /// <summary>
        /// 一级不良查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<QualityTypeDescDto>> GetQualityTypeDescList(GetInspectionTypeDescInput input)
        {
            var typeDescQuery = _qualityTypeDescRepository.GetAll().Where(s => s.IsUsed != InspectionItemInfo.IsUseds.已删除);
            var count = typeDescQuery.Count();
            typeDescQuery = typeDescQuery.OrderByDescending(e => e.CreationTime).PageBy(input);
            var result = ObjectMapper.Map<List<QualityTypeDescDto>>(typeDescQuery).ToList();
            return new PagedResultDto<QualityTypeDescDto>(count, result);
        }
        /// <summary>
        /// 二级不良查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<QualityItemInfoOutDto>> GetQualityItemInfoList(GetInspectionItemInfoInput input)
        {
            var itemInfoQuery = from qi in _qualityItemInfoRepository.GetAll().Where(s => s.IsUsed != InspectionItemInfo.IsUseds.已删除)
                                join qtd in _qualityTypeDescRepository.GetAll()
                                on qi.TypeId equals qtd.Id
                                where qtd.Id == input.TypeId
                                select qi;
            var count = itemInfoQuery.Count();
            itemInfoQuery = itemInfoQuery.OrderByDescending(e => e.CreationTime).PageBy(input);
            var result = ObjectMapper.Map<List<QualityItemInfoOutDto>>(itemInfoQuery).ToList();
            return new PagedResultDto<QualityItemInfoOutDto>(count, result);
        }
        /// <summary>
        /// 不良严重程度新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateQualitySeverityDesc(QualitySeverityDescDto input)
        {
            if (input.Id == Guid.Empty)
            {
                input.Id = await CreateQualitySeverityDesc(input);
            }
            else
            {
                await UpdateQualitySeverityDesc(input);
            }
        }
        /// <summary>
        /// 不良严重程度insert
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<Guid> CreateQualitySeverityDesc(QualitySeverityDescDto input)
        {
            var qualitySeverityDesc = new QualitySeverityDesc()
            {
                Id = Guid.NewGuid(),
                SeverityName = input.SeverityName,
                SeverityDesc = input.SeverityDesc,
                IsUsed = (InspectionItemInfo.IsUseds)input.IsUsed
            };
            //for (int i = 0; i < input.CCRole.Length; i++)
            //{
            //    var qualitySeverityRole = new QualitySeverityRole()
            //    {
            //        Id = Guid.NewGuid(),
            //        SeverityId = qualitySeverityDesc.Id,
            //        RoleId = input.CCRole[i]
            //    };
            //    await _qualitySeverityRoleRepository.InsertAsync(qualitySeverityRole);
            //}
            var workFlow = _affairRemindRepository.FirstOrDefault(s => s.AffairCode == qualitySeverityDesc.Id.ToString());
            if (workFlow == null)
            {
                var role = _roleManager.Roles.ToList();
                AffairRemind temp = new AffairRemind();
                temp.AffairCode = qualitySeverityDesc.Id.ToString();
                temp.AffairType = "质量管理";
                temp.RoleList = string.Join(",", input.CCRole);
                temp.RoleListDesc = string.Join(",", role.Where(s => temp.RoleList.Contains(s.Id.ToString())).Select(s => s.DisplayName));
                temp.IsOpen = true;
                temp.Isdefault = true;
                _affairRemindRepository.Insert(temp);
            }
            else
            {
                throw new UserFriendlyException("数据错误，请检查数据库");
            }
            return await _qualitySeverityDescRepository.InsertAndGetIdAsync(qualitySeverityDesc);
        }
        /// <summary>
        /// 不良重程度update
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task UpdateQualitySeverityDesc(QualitySeverityDescDto input)
        {
            var qualitySeverityDesc = await _qualitySeverityDescRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
            if (qualitySeverityDesc != null)
            {
                qualitySeverityDesc.SeverityName = input.SeverityName;
                qualitySeverityDesc.SeverityDesc = input.SeverityDesc;
                qualitySeverityDesc.IsUsed = (InspectionItemInfo.IsUseds)input.IsUsed;

                await _qualitySeverityDescRepository.UpdateAsync(qualitySeverityDesc);
            }
            //await _qualitySeverityRoleRepository.DeleteAsync(p => p.SeverityId == input.Id);
            //for (int i = 0; i < input.CCRole.Length; i++)
            //{
            //    var qualitySeverityRole = new QualitySeverityRole()
            //    {
            //        Id = Guid.NewGuid(),
            //        SeverityId = input.Id,
            //        RoleId = input.CCRole[i]
            //    };
            //    await _qualitySeverityRoleRepository.InsertAsync(qualitySeverityRole);
            //}
            var workFlow = _affairRemindRepository.FirstOrDefault(s => s.AffairCode == input.Id.ToString());
            if (workFlow != null)
            {
                var role = _roleManager.Roles.ToList();
                workFlow.RoleList = string.Join(",", input.CCRole);
                workFlow.RoleListDesc = string.Join(",", role.Where(s => workFlow.RoleList.Contains(s.Id.ToString())).Select(s => s.DisplayName));
                _affairRemindRepository.Update(workFlow);
            }
            else
            {
                throw new UserFriendlyException("数据错误，请检查数据库");
            }
        }
        /// <summary>
        /// 一级不良新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateQualityTypeDesc(QualityTypeDescDto input)
        {

            if (input.Id == Guid.Empty)
            {
                await CreateQualityTypeDesc(input);
            }
            else
            {
                await UpdateQualityTypeDesc(input);
            }
        }
        /// <summary>
        /// 一级不良insert
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task CreateQualityTypeDesc(QualityTypeDescDto input)
        {
            var qualityTypeDesc = new QualityTypeDesc()
            {
                Id = Guid.NewGuid(),
                TypeName = input.TypeName,
                IsUsed = (InspectionItemInfo.IsUseds)input.IsUsed
            };
            await _qualityTypeDescRepository.InsertAndGetIdAsync(qualityTypeDesc);
        }
        /// <summary>
        /// 一级不良update
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task UpdateQualityTypeDesc(QualityTypeDescDto input)
        {
            var qualityTypeDesc = await _qualityTypeDescRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
            if (qualityTypeDesc != null)
            {
                qualityTypeDesc.TypeName = input.TypeName;
                qualityTypeDesc.IsUsed = (InspectionItemInfo.IsUseds)input.IsUsed;

                await _qualityTypeDescRepository.UpdateAsync(qualityTypeDesc);
            }
        }
        /// <summary>
        /// 二级不良新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateCreateQualityItemInfo(QualityItemInfoDto input)
        {

            if (input.Id == Guid.Empty)
            {
                await CreateQualityItemInfo(input);
            }
            else
            {
                await UpdateQualityItemInfo(input);
            }
        }
        /// <summary>
        /// 二级不良insert
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task CreateQualityItemInfo(QualityItemInfoDto input)
        {
            var qualityItemInfo = new QualityItemInfo()
            {
                Id = Guid.NewGuid(),
                TypeId = input.TypeId,
                ItemName = input.ItemName,
                IsUsed = (InspectionItemInfo.IsUseds)input.IsUsed
            };
            await _qualityItemInfoRepository.InsertAndGetIdAsync(qualityItemInfo);
        }
        /// <summary>
        /// 二级不良update
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task UpdateQualityItemInfo(QualityItemInfoDto input)
        {
            var qualityItemInfo = await _qualityItemInfoRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
            if (qualityItemInfo != null)
            {
                qualityItemInfo.TypeId = input.TypeId;
                qualityItemInfo.ItemName = input.ItemName;
                qualityItemInfo.IsUsed = (InspectionItemInfo.IsUseds)input.IsUsed;

                await _qualityItemInfoRepository.UpdateAsync(qualityItemInfo);
            }
        }
        /// <summary>
        /// 不良严重程度删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteQualitySeverityDesc(Guid id)
        {
            var qualitySeverityDesc = _qualitySeverityDescRepository.FirstOrDefaultAsync(s=>s.Id == id).Result;
            if (qualitySeverityDesc != null)
            {
                qualitySeverityDesc.IsUsed = (InspectionItemInfo.IsUseds)2;
                await _qualitySeverityDescRepository.UpdateAsync(qualitySeverityDesc);
                var workFlow = _affairRemindRepository.FirstOrDefault(s => s.AffairCode == id.ToString());
                if (workFlow != null)
                {
                    await _affairRemindRepository.DeleteAsync(workFlow);
                }
            }
        }
        /// <summary>
        /// 一级不良删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteQualityTypeDesc(Guid id)
        {
            var qualityTypeDesc = await _qualityTypeDescRepository.FirstOrDefaultAsync(p => p.Id == id);
            if (qualityTypeDesc != null)
            {
                qualityTypeDesc.IsUsed = InspectionItemInfo.IsUseds.已删除;
                await _qualityTypeDescRepository.UpdateAsync(qualityTypeDesc);
            }
            var qualityItemInfo = await _qualityItemInfoRepository.FirstOrDefaultAsync(p => p.TypeId == id);
            if (qualityItemInfo != null)
            {
                qualityItemInfo.IsUsed = InspectionItemInfo.IsUseds.已删除;
                await _qualityItemInfoRepository.UpdateAsync(qualityItemInfo);
            }
        }
        /// <summary>
        /// 二级不良删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteQualityItemInfo(Guid id)
        {
            var qualityItemInfo = await _qualityItemInfoRepository.FirstOrDefaultAsync(c => c.Id == id);
            if (qualityItemInfo != null)
            {
                qualityItemInfo.IsUsed = InspectionItemInfo.IsUseds.已删除;
                await _qualityItemInfoRepository.UpdateAsync(qualityItemInfo);
            }
        }
    }
}
